package ch.cm.ctrlurhome.gcm.sender;

import java.io.IOException;

import org.apache.log4j.Logger;

import ch.cm.ctrlurhome.gcm.exceptions.ReceiverIDHasChangedException;

import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.Message.Builder;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;

public class Push2AndroidSender {

    private static Logger logger = Logger.getLogger(Push2AndroidSender.class);

    private static final String COLLAPSE_KEY = "collapseKey";
    private static final String MESSAGE_KEY = "message";
    private static final int TIME_2_LIVE = 50;
    private static final int SEND_RETRIES = 1;
    private static final boolean DELAY_WITH_IDLE = true;

    private Sender sender;
    private Message message;
    MulticastResult multicastResult;
    
    public Push2AndroidSender(String googleAPIKey){
        this.sender = new Sender(googleAPIKey);
    }
    
    /**
     * 
     * @param senderID
     * @param messageContent
     * @return OK, errorCode, new ID
     * @throws IOException
     */
    public String sendMessage2singleMobile(String receiverID, String messageContent) throws IOException {
        logger.debug("sendMessage2singleMobile");
        message = buildAMessage(messageContent);
        logger.debug("Try 2 send to a SinleDevice: "+ receiverID);
        Result result = sender.send(message, receiverID, SEND_RETRIES);
        String errorCodeName = result.getErrorCodeName();
        if (errorCodeName!= null) {
            logger.error("Message could not be sendet: "+errorCodeName);;
            return errorCodeName;
        }
        String canonicalRegistrationId = result.getCanonicalRegistrationId();
        if (canonicalRegistrationId!= null) {
            logger.error("CanonicalRegistrationId changed: "+ canonicalRegistrationId);
            throw new ReceiverIDHasChangedException(canonicalRegistrationId);
        }
        return "OK";
    }

    private Message buildAMessage(String messageContent) {
        logger.debug("Build a GCM-Message");
        Builder builder = new Message.Builder();
        builder.collapseKey(COLLAPSE_KEY);
        logger.debug("Time to live:" + TIME_2_LIVE);
        builder.timeToLive(TIME_2_LIVE);
        logger.debug("Delay with Idle: " + DELAY_WITH_IDLE);
        builder.delayWhileIdle(DELAY_WITH_IDLE);
        logger.debug("MessageContent: " + messageContent);
        builder.addData(MESSAGE_KEY, messageContent);
        return builder.build();
    }
}
